package com.warm.androidstudy.utils;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.target.Target;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * Created by Administrator on 2017/8/25.
 */

public class FileUtils {

    private static Context mContext;
    private static String mPermissionDescribe = "存储";
    private static String mSavePicUrl;

    /**
     * 判断外置sdcard是否可以正常使用
     */
    public static boolean isValidState() {
        //获取内部存储状态 -- 如果状态不是mounted，无法读写
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable();
    }

    /**
     * 保存图片(根据url获取图片)到外存缓存
     *
     * @param context
     * @param url
     * @param urlPath            是否是网络url图片资源，false表示不是
     * @param saveResultCallback
     */
    public static void savePhoto(final Context context, final String url, final boolean urlPath, final SaveResultCallback saveResultCallback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String path = url;//直接传递本地路径
                if (urlPath) {
                    path = FileUtils.getImagePath(url, context);//获得Glide图片缓存路径
                }
                //拷贝到指定路径
                if (isValidState()) {
                    //创建文件
                    File appDir = new File(Environment.getExternalStorageDirectory(), "internetHospital/");//应用的内部存储图片目录
                    if (!appDir.exists()) {
                        appDir.mkdir();
                    }
                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置以当前时间格式为图片名称
                    try {
                        //识别是否是GIF类型图片
                        String fileName = df.format(new Date()) + ".png";
//                        ImageHeaderParser.ImageType type = new ImageHeaderParser(new URL(url).openStream()).getType();
//                        if (ImageHeaderParser.ImageType.GIF.equals(type)) {
//                            fileName = df.format(new Date()) + ".gif";     // 0:普通类型；1：长图；2：全景图 3：GIF动图
//                        }
                        File file = new File(appDir, fileName);
                        String imagePath = appDir + "/" + fileName;
                        LogUtil.e("---保存的imagePath --- " + imagePath);

                        //拷贝文件
                        FileUtils.copyFile(path, imagePath);
                        //通知系统相册刷新
                        Intent intentBroadcast = new Intent(
                                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        intentBroadcast.setData(Uri.fromFile(file));
                        context.sendBroadcast(intentBroadcast);
                        LogUtil.e("---保存成功--- ");
                        saveResultCallback.onSavedSuccess();
                    } catch (Exception e) {
                        LogUtil.e("----saveImageToLocal: Exception --- ");
                        saveResultCallback.onSavedSuccess();
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    public interface SaveResultCallback {
        void onSavedSuccess();

        void onSavedFailed();
    }

    public static void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            LogUtil.e("----FileUtils --copyFile : Exception --- ");
            e.printStackTrace();
        }
    }

    /**
     * Glide 获得图片缓存路径
     */
    public static String getImagePath(String imgUrl, Context context) {
        String path = null;
        FutureTarget<File> future = Glide.with(context)
                .load(imgUrl)
                .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
        try {
            File cacheFile = future.get();
            path = cacheFile.getAbsolutePath();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * 保存图片到本地
     *
     * @param context
     */
    public static void savePicToLocal(Context context, String picUrl) {
        mContext = context;
        mSavePicUrl = picUrl;
        if (Build.VERSION.SDK_INT >= 23) {//6.0  // 检测权限
            PermissionUtil.dexterMultipleCheck(mContext, permissionsListener, mPermissionDescribe, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        } else {
            saveImageToLocal(mContext, mSavePicUrl);//保存图片到本地
        }
    }

    /**
     * 存储权限申请的监听
     */
    private static MultiplePermissionsListener permissionsListener = new MultiplePermissionsListener() {
        @Override
        public void onPermissionsChecked(MultiplePermissionsReport report) {
            if (report.areAllPermissionsGranted()) {
                saveImageToLocal(mContext, mSavePicUrl);//保存图片到本地
            }
        }

        @Override
        public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
            LogUtil.e("onPermissionRationale", "无授权&&非第一次授权&&非勾选“不再提醒” 时会打开。");
            PermissionUtil.onPermissionRationaleShouldBeShown(mContext, token, "应用需要" + mPermissionDescribe + "权限,请开启");
        }
    };


    private static void saveImageToLocal(Context context, String picUrl) {
        FileUtils.savePhoto(context, picUrl, true, new SaveResultCallback() {
            @Override
            public void onSavedSuccess() {
                ToastUtil.showMessage("保存成功，可在本地相册中查看");//可在相册/InternetHospital/savePhoto文件中查看
            }

            @Override
            public void onSavedFailed() {
                ToastUtil.showMessage("保存失败");
            }
        });
    }
}
